
package managedBean;


import Merlion.CRM.entity.BillingAddressEntity;
import Merlion.CRM.entity.ClientEntity;
import Merlion.CRM.entity.LineEntryEntity;

//import CRM.ProductCRMEntity;
import Merlion.CRM.entity.PricebookEntity;
import Merlion.CRM.bean.SalesLeadModuleRemote;
import Merlion.CRM.bean.SalesOrderProcessingModuleRemote;
import Merlion.CRM.entity.ShippingAddressEntity;
import Merlion.SCM.bean.InventoryMovementsManagementBeanRemote;
import Merlion.util.state.AddressState;
import Merlion.util.state.ClientState;
import Merlion.util.state.ContactState;
import Merlion.util.state.DeliveryOrderState;
import Merlion.util.state.LineEntryState;
import Merlion.util.state.ProductState;
import Merlion.util.state.SalesDocumentState;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.ServletException;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author anindya
 */
@ManagedBean(name="DeliveryOrderManagedBean")
@ViewScoped
public class DeliveryOrderManagedBean implements Serializable {
 
    private LineEntryState lineEntry = new LineEntryState();

    private List<LineEntryState> lineEntryList = new ArrayList<LineEntryState>();
    
    private Long purchaseOrderInput;
    private DeliveryOrderState newDeliveryOrder= new DeliveryOrderState();
    private List<SalesDocumentState> salesOrderList;
    private DeliveryOrderState selectedDeliveryOrder;
    private DeliveryOrderState[] selectedDeliveryOrders;
    
    private List<LineEntryState> productList;
    private DeliveryOrderState selectedViewDeliveryOrder;
    private List<ClientState> clientList;
    private List<DeliveryOrderState> deliveryOrderList;
    private List<LineEntryState> selectedProductList;
    private DeliveryOrderState selectedPrintDeliveryOrders;
    private boolean editMode;
    private  Long    salesOrderInput;
    private  Long deliveryOrderInput;
    private Long selectedPrintDeliveryOrderID;
    
    private Long productId;
    private int quantity;
    private double listPrice;
    private String type;
    private PricebookEntity pricebook;
    private List<PricebookEntity> pricebookList;
    private double totalPrice;
    private String pricingType;
 
    private List<AddressState> billingAddress;
    private List<AddressState> shippingAddress;
    private AddressState selectedBillingAddress;
    private AddressState selectedShippingAddress;
    private int maxQuantity;
    private List<ContactState> contactList;
    private List<ContactState> selectedContactList;   
    private List<DeliveryOrderState> doList;
    private DeliveryOrderState newShipGroup = new DeliveryOrderState();
    private String shippingCompany;
    
    @EJB
    private SalesOrderProcessingModuleRemote sop;
    @EJB
    private SalesLeadModuleRemote smb;
    @EJB
    private InventoryMovementsManagementBeanRemote imm;

    public List<DeliveryOrderState> getDoList() {
        if(doList==null){
            doList = sop.viewDeliveryOrders();
        }
        return doList;
    }

    public void setDoList(List<DeliveryOrderState> doList) {
        this.doList = doList;
    }
 
    
    public List<ContactState> getSelectedContactList() {
        if(selectedContactList==null){
            if(selectedViewDeliveryOrder!=null){
                selectedContactList = smb.viewContactsForClients(selectedViewDeliveryOrder.getClientId());
            }
        }
        return selectedContactList;
    }

    public void setSelectedContactList(List<ContactState> selectedContactList) {
        this.selectedContactList = selectedContactList;
    }

    public String reinit(){

        lineEntry = new LineEntryState();
        
        return null;
    }
    
    public List<LineEntryState> getProductList() {

        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        System.out.println("Get Product List");               
        return productList;
    }

    public void setProductList(List<LineEntryState> productList) {
        this.productList = productList;
    }

    public List<SalesDocumentState> getSalesOrderList() {
        if(salesOrderList==null){
            salesOrderList = sop.viewSalesOrdersForDO();
        }
        return salesOrderList;
    }

    public void setSalesOrderList(List<SalesDocumentState> salesOrderList) {
        this.salesOrderList = salesOrderList;
    }

    public List<LineEntryState> getSelectedProductList() {
        return selectedProductList;
    }

    public void setSelectedProductList(List<LineEntryState> selectedProductList) {
        this.selectedProductList = selectedProductList;
    }


    public List<ClientState> getClientList() {
        if(clientList==null){
            clientList = smb.viewCustomers();
        }
        return clientList;
    }

    public void setClientList(List<ClientState> clientList) {
        this.clientList = clientList;
    }

    public DeliveryOrderState getNewDeliveryOrder() {
        return newDeliveryOrder;
    }

    public void setNewDeliveryOrder(DeliveryOrderState newDeliveryOrder) {
        this.newDeliveryOrder = newDeliveryOrder;
    }

    public DeliveryOrderState getSelectedViewDeliveryOrder() {
        return selectedViewDeliveryOrder;
    }

    public void setSelectedViewDeliveryOrder(DeliveryOrderState selectedViewDeliveryOrder) {
        this.selectedViewDeliveryOrder = selectedViewDeliveryOrder;
        if(selectedViewDeliveryOrder!=null){System.out.println("View DeliveryOrder NOT NULL");}
        this.selectedViewDeliveryOrder = selectedViewDeliveryOrder;
        System.out.println("ID : "+selectedViewDeliveryOrder.getId());
        selectedProductList=sop.viewProductListforDeliveryOrder(selectedViewDeliveryOrder.getId());
        this.setSelectedProductList(selectedProductList);
    }

    public void initView3(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (deliveryOrderList == null) {
            deliveryOrderList = sop.viewDeliveryOrders();
        }
    }

    public void initView2(PhaseEvent event){
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if(deliveryOrderList == null)
        {
            deliveryOrderList = imm.viewDeliveryOrders();
        }
    }
    
    public void initView(PhaseEvent event){
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    }

    public DeliveryOrderManagedBean() {

        lineEntry = new LineEntryState();

    }

       
    public LineEntryState getLineEntry() {
        return lineEntry;
    }

    public void setLineEntry(LineEntryState lineEntry) {
        this.lineEntry = lineEntry;
    }

    public List<LineEntryState> getLineEntryList() {
        System.out.println("GET LINE ENTRY LIST");
        return lineEntryList;
    }

    public void setLineEntryList(List<LineEntryState> lineEntryList) {
        System.out.println("SET LINE ENTRY LIST");
        this.lineEntryList = lineEntryList;
    }
    
    
    public void addDeliveryOrder(ActionEvent event){
        
        System.out.println(":::WEB::: Add Sales Order2");
        
        Long soID       =   salesOrderInput;
        Date dateIssued =   newDeliveryOrder.getDateIssued();
        Long clientID   =   newDeliveryOrder.getClientId();
        Long contactID  =   newDeliveryOrder.getContactId();
        String status   =   newDeliveryOrder.getStatus();
       
        
        String billStreet   = newDeliveryOrder.getBillingStreet();
        String billState    = newDeliveryOrder.getBillingState();
        String billCity     = newDeliveryOrder.getBillingCity();
        String billCode     = newDeliveryOrder.getBillingCode();
        String billCountry  = newDeliveryOrder.getBillingCountry();

        String shipStreet   = newDeliveryOrder.getShippingStreet();
        String shipState    = newDeliveryOrder.getShippingState();
        String shipCity     = newDeliveryOrder.getShippingCity();
        String shipCode     = newDeliveryOrder.getShippingCode();
        String shipCountry  = newDeliveryOrder.getShippingCountry();
    
        String description = newDeliveryOrder.getDescription();
    
        String docName     = newDeliveryOrder.getDocumentName();

        
        System.out.println("WEB:DOCNAME "+docName);
        String shippingMethod   = newDeliveryOrder.getShippingMethod();
        String shippingRule     = newDeliveryOrder.getShippingRule();
        String paymentMethod    = newDeliveryOrder.getPaymentMethod();        
        String freightCostRule  = newDeliveryOrder.getFreightCostRule();
        Date dueDate = newDeliveryOrder.getDueDate();
        
        Long billingId = Long.parseLong("0");
         if(newDeliveryOrder.getBillingId()!=null){
             System.out.println("Billing ID not null!");
             billingId = newDeliveryOrder.getBillingId();
             smb.editBillingAddress(billingId, billStreet, billCity, billState, billCode, billCountry);
         }
         Long shippingId = Long.parseLong("0");
         if(newDeliveryOrder.getShippingId()!=null){
             System.out.println("Shipping ID not null!");
             shippingId = newDeliveryOrder.getShippingId();
             smb.editShippingAddress(shippingId, shipStreet, shipCity, shipState, shipCode, shipCountry);
         }
        System.out.println("Customer ID is : "+clientID);

        if(!lineEntryList.isEmpty()){System.out.println("Products not null");
         System.out.println("ID is : "+lineEntryList.get(0).getId());
        }
        System.out.println(":::WEB::: Calling addDeliveryOrder()");


        imm.createDeliveryOrder(soID, clientID, contactID, dateIssued, lineEntryList, 
                billingId, shippingId, description, docName, shippingMethod, 
                shippingRule, paymentMethod, freightCostRule, pricingType);
        
        System.out.println(":::WEB::: Add Delivery Order done");
        
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("addDeliveryOrderStatus.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        
        
    }

    public Long getDeliveryOrderInput() {
        return deliveryOrderInput;
    }

    public void setDeliveryOrderInput(Long deliveryOrderInput) {
        this.deliveryOrderInput = deliveryOrderInput;
    }

    public DeliveryOrderState getNewShipGroup() {
        return newShipGroup;
    }

    public void setNewShipGroup(DeliveryOrderState newShipGroup) {
        this.newShipGroup = newShipGroup;
    }
    
    
    
   public void addShipGroup(ActionEvent event){
        
        System.out.println(":::WEB::: Add Sales Order2");
        
        Long soID       =   deliveryOrderInput;
        Date dateIssued =   newShipGroup.getDateIssued();
        Long clientID   =   newShipGroup.getClientId();
        Long contactID  =   newShipGroup.getContactId();
        String status   =   newShipGroup.getStatus();
       
        
        String billStreet   = newShipGroup.getBillingStreet();
        String billState    = newShipGroup.getBillingState();
        String billCity     = newShipGroup.getBillingCity();
        String billCode     = newShipGroup.getBillingCode();
        String billCountry  = newShipGroup.getBillingCountry();

        String shipStreet   = newShipGroup.getShippingStreet();
        String shipState    = newShipGroup.getShippingState();
        String shipCity     = newShipGroup.getShippingCity();
        String shipCode     = newShipGroup.getShippingCode();
        String shipCountry  = newShipGroup.getShippingCountry();
    
        String description = newShipGroup.getDescription();
    
        String docName     = newShipGroup.getDocumentName();

        
        System.out.println("WEB:DOCNAME "+docName);
        String shippingMethod   = newShipGroup.getShippingMethod();
        String shippingRule     = newShipGroup.getShippingRule();
        String paymentMethod    = newShipGroup.getPaymentMethod();        
        String freightCostRule  = newShipGroup.getFreightCostRule();
        Date dueDate = newShipGroup.getDueDate();
        
        Long billingId = Long.parseLong("0");
         if(newShipGroup.getBillingId()!=null){
             System.out.println("Billing ID not null!");
             billingId = newShipGroup.getBillingId();
             smb.editBillingAddress(billingId, billStreet, billCity, billState, billCode, billCountry);
         }
         Long shippingId = Long.parseLong("0");
         if(newShipGroup.getShippingId()!=null){
             System.out.println("Shipping ID not null!");
             shippingId = newShipGroup.getShippingId();
             smb.editShippingAddress(shippingId, shipStreet, shipCity, shipState, shipCode, shipCountry);
         }
        System.out.println("Customer ID is : "+clientID);

        if(!lineEntryList.isEmpty()){System.out.println("Products not null");
         System.out.println("ID is : "+lineEntryList.get(0).getId());
        }
        System.out.println(":::WEB::: Calling addShippingGroup()");

        sop.addShippingGroup(soID, contactID, 
                shippingMethod, shippingRule, 
                freightCostRule, billingId, shippingId,  lineEntryList);
       
        
        System.out.println(":::WEB::: Add Shipping group done");
        
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("addDeliveryOrderStatus.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        
        
    }
    
    public void onEditRow (RowEditEvent event){
              
        System.out.println(":::WEB::: On Edit Row");
        
        DeliveryOrderState eDocument = (DeliveryOrderState)event.getObject();
        
        if(eDocument!=null){
            System.out.println(":::WEB::: Edited document not null");
            String eStatus = eDocument.getStatus();
    
            Date eDateIssued    = eDocument.getDateIssued();
            Long eClientId       =   eDocument.getClientId();
            Long eContactId      =   eDocument.getContactId();
            Long doId           =   eDocument.getId();
            System.out.println("Delivery Order ID "+doId);
            Long soID           =   eDocument.getSalesOrderId();
            System.out.println("Sales Order ID is "+soID);
            
            String eBillStreet  =   eDocument.getBillingStreet();
            String eBillState   =   eDocument.getBillingState();
            String eBillCity    =   eDocument.getBillingCity();
            String eBillCode    =   eDocument.getBillingCode();
            String eBillCountry =   eDocument.getBillingCountry();
            Long eBillId        =   eDocument.getBillingId();
            smb.editBillingAddress(eBillId, eBillStreet, eBillCity, eStatus, eBillCode, eBillCountry);
            
            String eShipStreet  =   eDocument.getShippingStreet();
            String eShipState   =   eDocument.getShippingState();
            String eShipCity    =   eDocument.getShippingCity();
            String eShipCode    =   eDocument.getShippingCode();
            String eShipCountry =   eDocument.getShippingCountry();
            Long eShipId        =   eDocument.getShippingId();
            smb.editShippingAddress(eShipId, eShipStreet, eShipCity, eStatus, eShipCode, eShipCountry);
            
            String eDesc            = eDocument.getDescription();
            String eDocName         = eDocument.getDocumentName();
            String eShippingMethod  = eDocument.getShippingMethod();
            String eShippingRule    = eDocument.getShippingRule();
            Date eDueDate           = eDocument.getDueDate();
          
            String ePaymentMethod   = eDocument.getPaymentMethod();
            String eFreightCostRule = eDocument.getFreightCostRule();

            System.out.println(":::WEB::: Calling Edit Sales Order");
            imm.updateDeliveryOrder(doId, soID, eClientId, eContactId, eDateIssued,
                     eDesc, eDocName, eShippingMethod, eShippingRule,
                    ePaymentMethod,  eFreightCostRule, pricingType, eStatus, eBillId, eShipId);
        }
        else{
            System.out.println(":::WEB::: Edited sales order is null");
        }
        
    }
    
    public void onEditLineEntry(RowEditEvent event) {

        System.out.println(":::WEB::: On Edit Line Entry");
        LineEntryState line = (LineEntryState) event.getObject();

        if (line != null) {
            System.out.println(":::WEB::: Edited line entry not null");
            int indicativeLeadTime = line.getIndicativeLeadTime();
            Long id = line.getId();
            int amtShipped = line.getAmountShipped();
            int amtInvoiced = line.getAmountInvoiced();
            System.out.println(":::WEB::: Calling Update Lead Time");
            sop.updateLineEntry(id, indicativeLeadTime, amtShipped, amtInvoiced);
        } else {
            System.out.println(":::WEB::: Edited line entry is null");
        }

    }

    
    public void deleteDeliveryOrders() {
        System.out.println(":::WEB::: Delete Delivery Orders");

        if (selectedDeliveryOrders != null) {
            System.out.println(":::WEB::: If selected Delivery orders not null");
            for (int i = 0; i < selectedDeliveryOrders.length; i++) {
                System.out.println("selectedDeliveryOrders i: " + i + " - " + selectedDeliveryOrders[i].getId());
                imm.deleteDeliveryOrder(selectedDeliveryOrders[i].getId());
            }
        }else{
            System.out.println(":::WEB::: Selected Delivery orders are null");
        }
        
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("deliveryOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
    }
    
    public void cancelDelete() {
        for (DeliveryOrderState sdState : selectedDeliveryOrders) {
            sdState = null;
        }
        if(selectedDeliveryOrders==null){
            System.out.println(":::WEB::: Deletion of Purchase Orders cancelled");
 
       }else{
            System.out.println(":::WEB::: Deletion of Purchase Orders are not cancelled");
        }
           
    }
    
    
    
    public void delete(ActionEvent Event){
        
        System.out.println(":::WEB::: Delete Delivery Order"); 
        
        if(selectedDeliveryOrder!=null){
            System.out.println(":::WEB::: Selected Delivery Order not null");
            Long DeliveryOrderId=selectedDeliveryOrder.getId();      
            System.out.println(":::WEB::: Delivery Order ID is : "+DeliveryOrderId);
            imm.withdrawDeliveryOrder(DeliveryOrderId);
            System.out.println(":::WEB::: Deletion done");
        }
        else{
            System.out.println(":::WEB::: Selected Delivery Order is null");
        }
        
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("deliveryOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }


    public Long getSalesOrderInput() {
        return salesOrderInput;
    }

    public void setSalesOrderInput(Long salesOrderInput) {
        this.salesOrderInput = salesOrderInput;
    }

    public DeliveryOrderState getSelectedDeliveryOrder() {
        return selectedDeliveryOrder;
    }

    public void setSelectedDeliveryOrder(DeliveryOrderState selectedDeliveryOrder) {
        this.selectedDeliveryOrder = selectedDeliveryOrder;
    }

    public DeliveryOrderState[] getSelectedDeliveryOrders() {
        return selectedDeliveryOrders;
    }

    public void setSelectedDeliveryOrders(DeliveryOrderState[] selectedDeliveryOrders) {
        this.selectedDeliveryOrders = selectedDeliveryOrders;
    }


    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public void save(ActionEvent event){
        System.out.println(":::WEB::: Save Edit SO");
        
        Long cDoID          =   selectedViewDeliveryOrder.getId();
        Date cDateIssued    =   selectedViewDeliveryOrder.getDateIssued();
        Long cClientID      =   selectedViewDeliveryOrder.getClientId();
        Long cContactID     =   selectedViewDeliveryOrder.getContactId();
        Long cSoID          =   selectedViewDeliveryOrder.getSalesOrderId();
        String cStatus      =   selectedViewDeliveryOrder.getStatus();

        
        String cBillStreet      = selectedViewDeliveryOrder.getBillingStreet();
         String cBillState      = selectedViewDeliveryOrder.getBillingState();
         String cBillCity       = selectedViewDeliveryOrder.getBillingCity();
         String cBillCode       = selectedViewDeliveryOrder.getBillingCode();
         String cBillCountry    = selectedViewDeliveryOrder.getBillingCountry();
         Long cBillId           = selectedViewDeliveryOrder.getBillingId();
         smb.editBillingAddress(cBillId, cBillStreet, cBillCity, cBillState, cBillCode, cBillCountry);

         String cShipStreet     = selectedViewDeliveryOrder.getShippingStreet();
         String cShipState      = selectedViewDeliveryOrder.getShippingState();
         String cShipCity       = selectedViewDeliveryOrder.getShippingCity();
         String cShipCode       = selectedViewDeliveryOrder.getShippingCode();
         String cShipCountry    = selectedViewDeliveryOrder.getShippingCountry();
         Long cShipId           = selectedViewDeliveryOrder.getShippingId();
         smb.editShippingAddress(cShipId, cShipStreet, cShipCity, cShipState, cShipCode, cShipCountry);
        
        
        String cDescription     = selectedViewDeliveryOrder.getDescription();
        String cDocName         = selectedViewDeliveryOrder.getDocumentName();
        String cShippingMethod  = selectedViewDeliveryOrder.getShippingMethod();
        String cShippingRule    = selectedViewDeliveryOrder.getShippingRule();
        String cPaymentMethod   = selectedViewDeliveryOrder.getPaymentMethod();
        String cFreightCostRule = selectedViewDeliveryOrder.getFreightCostRule();
        Date cDueDate           = selectedViewDeliveryOrder.getDueDate();

                  
        System.out.println("DO ID is :"+cDoID);
        System.out.println(":::WEB::: Calling edit DO");
        
        imm.updateDeliveryOrder(cDoID, cSoID, cClientID, 
                       cContactID, cDateIssued, cDescription, cDocName, 
                       cShippingMethod, cShippingRule, cPaymentMethod, 
                       cFreightCostRule, pricingType, cStatus, cBillId, cShipId);  

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("deliveryOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
    }

    
    public PricebookEntity getPricebook() {

        return pricebook;
    }

    public void setPricebook(PricebookEntity pricebook) {
        System.out.println("SET PRICEBOOK");

        this.pricebook = pricebook;

    }
    
    public double getTotalPrice() {
        return totalPrice;
    }
    
    public void setTotalPrice(double totalPrice) {
        System.out.println("Set total price");
        this.totalPrice = totalPrice;
    }
    
    public String getPricingType() {
        return pricingType;
    }
    
    public void setPricingType(String pricingType) {
        this.pricingType = pricingType;
    }
    
    public List<PricebookEntity> getPricebookList() {
        System.out.println("GET PRICEBOOK LIST");
        
        if (pricebookList == null) {            
           // if (lineEntry.getProduct() == null) {
                System.out.println("GET from bean");
                pricebookList = sop.getPricebookList();
         //   }
        }
        return pricebookList;
    }
    
    public void setPricebookList(List<PricebookEntity> pricebookList) {
        System.out.println("SET pricebook List");
        this.pricebookList = pricebookList;
    }
    
    public double getListPrice() {
        return listPrice;
    }
    
    public void setListPrice(double listPrice) {
        System.out.println("SET LIST PRICE");
        this.listPrice = listPrice;
    }
    
    public void handlePricebookChange() {
        System.out.println("HANDLE PRICEBOOK CHANGE");
        if (lineEntry.getPricebookId() != null) {
            System.out.println("Pricebook not null");
            System.out.println("Type " + type);
            System.out.println("quantity" + lineEntry.getQuantity());
            
            listPrice = sop.getListPrice(lineEntry.getQuantity(), type, lineEntry.getPricebookId());
            lineEntry.setPrice(listPrice);
            System.out.println(lineEntry.getPrice());
            double total = sop.getTotalPrice(lineEntry, pricingType);
            System.out.println("Total " + total);
            lineEntry.setTotalPrice(total);
        }
    }
    
    public void onRowEdit(RowEditEvent event) {
        
        System.out.println(":::WEB::: On Edit Row");
        LineEntryState eLine = (LineEntryState) event.getObject();
        int eQuantity = eLine.getQuantity();
        double newPrice = eLine.getPrice();
        eLine.setPrice(newPrice);
        eLine.setQuantity(eQuantity);
        double total = eLine.getPrice()*eLine.getQuantity();
       
        eLine.setTotalPrice(total);

    }
    
    public void handleProductChange() {
        System.out.println("HANDLE PRODUCT CHANGE");
        if (lineEntry.getItemId() != null) {

            System.out.println("Product is not empty");
          //  this.setBillingAddress(billingAddress);

            ProductState product = sop.searchProduct(lineEntry.getItemId());
            lineEntry.setItemName(product.getItemName());
            lineEntry.setBasePrice(product.getPrice());
            System.out.println("Product list is null?");
            if (getProductList()!= null) {
                System.out.println("Product List not null");
                System.out.println("item id: "+lineEntry.getItemId());
                for (Object o : productList) {
                    LineEntryState l = (LineEntryState) o;
                    System.out.println("Item id for product" +l.getItemId());
                    if (l.getItemId().equals(lineEntry.getItemId())){
                        
                        System.out.println("Item id found, setting the price");
                        lineEntry.setPrice(l.getPrice());
                        int orderedQuantity = l.getQuantity();
                        int amtInDelivery = l.getAmountInDeliveryOrder();
                        int quantityLeft = orderedQuantity - amtInDelivery;
                        lineEntry.setQuantity(quantityLeft);
                    
                        setMaxQuantity(l.getQuantity());
                        break;
                    }
                }
            }
    
            double total = lineEntry.getQuantity()*lineEntry.getPrice();
            lineEntry.setTotalPrice(total);
        }
        
    }

    public List<DeliveryOrderState> getDeliveryOrderList() {
        return deliveryOrderList;
    }

    public void setDeliveryOrderList(List<DeliveryOrderState> deliveryOrderList) {
        this.deliveryOrderList = deliveryOrderList;
    }

    public int getMaxQuantity() {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        System.out.println("Max qty : "+maxQuantity);
        return maxQuantity;
    }

    public void setMaxQuantity(int maxQuantity) {
        this.maxQuantity = maxQuantity;
    }
    
    
    public int getQuantity() {
        return quantity;
    }
    
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String type) {
        this.type = type;
    }

    public List<AddressState> getBillingAddress() {
        if(billingAddress==null){
            billingAddress = sop.getBillingAddressList();
        }
        return billingAddress;
    }

    public void setBillingAddress(List<AddressState> billingAddress) {
        this.billingAddress = billingAddress;
    }

    public List<AddressState> getShippingAddress() {
        if(shippingAddress==null){
            shippingAddress = sop.getShippingAddressList();
        }
        return shippingAddress;
    }

    public void setShippingAddress(List<AddressState> shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

    public List<ContactState> getContactList() {
        if(contactList==null){
            contactList = smb.viewContacts();
        }
        return contactList;
    }

    public void setContactList(List<ContactState> contactList) {
        this.contactList = contactList;
    } 
    
    public void handleClientChange() {
        System.out.println("Handle client change");
        if (newDeliveryOrder.getClientId() != null) {
            ClientState clState = smb.searchClient(newDeliveryOrder.getClientId());
            String bType = clState.getBusinessType();
            this.setType(bType);
            
            if(clState.getClientType().equals("CU")){
            System.out.println("Set billing and shipping address");
            List<AddressState> addressList = clState.getAddressList();
            List<ContactState> cList = smb.viewContactsForClients(clState.getId());
            List<AddressState> billingAddressList  =  new ArrayList<AddressState>();
            List<AddressState> shippingAddressList = new ArrayList<AddressState>();
            for(Object o : addressList){
                AddressState as = (AddressState) o;
                if(as.getType().equals("B")){
                    billingAddressList.add(as);
                }else if(as.getType().equals("S")){
                    shippingAddressList.add(as);
                }
            }
            this.setBillingAddress(billingAddressList);
            this.setShippingAddress(shippingAddressList);
            this.setContactList(cList);
            }
        }
    }

    
    
    public void handlePriceChange() {
        System.out.println("Handle price change");
        if (lineEntry.getPrice() != 0) {
            System.out.println("Price " + lineEntry.getPrice());
            double total = lineEntry.getQuantity()*lineEntry.getPrice();
            lineEntry.setTotalPrice(total);
        }
    }
    
        
    public void handleQuantityChange() {
        System.out.println("Handle quantity change");
        if (lineEntry.getQuantity() != 0) {
            System.out.println("Price " + lineEntry.getQuantity());
            double total = lineEntry.getQuantity()*lineEntry.getPrice();
            lineEntry.setTotalPrice(total);
            lineEntry.setAmountInDeliveryOrder(lineEntry.getQuantity());
        }
    }
    
    public void handleSalesDocumentChange(){
        System.out.println("HANDLE SALES DOCUMENT CHANGE");
        if(salesOrderInput!=null){
            SalesDocumentState soState = sop.searchSalesOrder(salesOrderInput);
            Long salesDocClient = soState.getClientId();
            System.out.println("Sales doc client : "+salesDocClient);
            newDeliveryOrder.setClientId(salesDocClient);
            ClientState clState = smb.searchClient(newDeliveryOrder.getClientId());
            String bType = clState.getBusinessType();
            this.setType(bType);
            String pType = soState.getPricingType();
            this.setPricingType(pType);
            
            handleClientChange();
            
            newDeliveryOrder.setShippingId(soState.getShippingId());
            newDeliveryOrder.setBillingId(soState.getBillingId());
            
            handleShippingAddressChange();
            handleBillingAddressChange();
            System.out.println("Set delivery and payment information");
            newDeliveryOrder.setShippingRule(soState.getShippingRule());
            newDeliveryOrder.setShippingMethod(soState.getShippingMethod());
            newDeliveryOrder.setFreightCostRule(soState.getFreightCostRule());
            newDeliveryOrder.setPaymentMethod(soState.getPaymentMethod());
      
          
            System.out.println("Getting line entry list from quotation");
            Collection<LineEntryEntity> collectionList = soState.getLineEntryList();
            List<LineEntryEntity> list = new ArrayList<LineEntryEntity>(collectionList);
            List<LineEntryState> newList = new ArrayList<LineEntryState>();
            for(Object o : list){
                LineEntryEntity line = (LineEntryEntity) o;
                LineEntryState a = new LineEntryState();
                a.setBasePrice(line.getBasePrice());
                a.setItemId(line.getItemId());
                a.setTotalPrice(line.getTotalLinePrice());
                a.setQuantity(line.getQuantity());
                a.setPrice(line.getPrice());
                a.setPricebookId(line.getPricebookId());
                a.setIndicativeLeadTime(line.getLeadTime());
                a.setAmountInDeliveryOrder(line.getAmountInDeliveryOrder());
                a.setItemName(line.getItemName());
                newList.add(a);
            }
           
           // this.setLineEntryList(newList);   
            this.setProductList(newList);
            if(getProductList()!=null){
                System.out.println("Product list not null.");
            }
            
        }
    }

    
    public void handleSalesDocumentChange2(){
        System.out.println("HANDLE SALES DOCUMENT CHANGE");
        if(deliveryOrderInput!=null){
            DeliveryOrderState doState = imm.searchDeliveryOrder(deliveryOrderInput);
            Long salesDocClient = doState.getClientId();
            System.out.println("Sales doc client : "+salesDocClient);
            newShipGroup.setClientId(salesDocClient);
            ClientState clState = smb.searchClient(doState.getClientId());
            List<ContactState> cList = smb.viewContactsForClients(clState.getId());
            this.setContactList(cList);
            
            String bType = clState.getBusinessType();
            this.setType(bType);
            String pType = doState.getPricingType();
            this.setPricingType(pType);
            
            handleClientChange();
            
            newShipGroup.setShippingId(doState.getShippingId());
            newShipGroup.setBillingId(doState.getBillingId());
            
            handleShippingAddressChange2();
            handleBillingAddressChange2();
            System.out.println("Set delivery and payment information");
            newShipGroup.setShippingRule(doState.getShippingRule());
            newShipGroup.setShippingMethod(doState.getShippingMethod());
            newShipGroup.setFreightCostRule(doState.getFreightCostRule());
            newShipGroup.setPaymentMethod(doState.getPaymentMethod());
     
          
            System.out.println("Getting line entry list from salesOrder");
            
            List<LineEntryEntity> list = doState.getLineEntryList();
            List<LineEntryState> newList = new ArrayList<LineEntryState>();
            for(Object o : list){
                LineEntryEntity line = (LineEntryEntity) o;
                LineEntryState a = new LineEntryState();
                a.setBasePrice(line.getBasePrice());
                a.setItemId(line.getItemId());
                a.setTotalPrice(line.getTotalLinePrice());
                a.setQuantity(line.getQuantity());
                a.setPrice(line.getPrice());
                a.setPricebookId(line.getPricebookId());
                a.setIndicativeLeadTime(line.getLeadTime());
                a.setAmountInDeliveryOrder(line.getAmountInDeliveryOrder());
                a.setItemName(line.getItemName());
                newList.add(a);
            }
           
 
            this.setProductList(newList);
            if(getProductList()!=null){
                System.out.println("Product list not null.");
            }
            

            
        }
    }

    public void handleBillingAddressChange2() {
        System.out.println("Handle billing Address Change");

        if (newShipGroup.getBillingId() != null) {
            AddressState ba = sop.searchBillingAddress(newShipGroup.getBillingId());
            newShipGroup.setBillingStreet(ba.getStreet());
            newShipGroup.setBillingCity(ba.getCity());
            newShipGroup.setBillingState(ba.getState());
            newShipGroup.setBillingCode(ba.getCode());
            newShipGroup.setBillingCountry(ba.getCountry());
        }

    }
    
    public void handleBillingAddressChange(){
        System.out.println("Handle billing Address Change");
       
        if(newDeliveryOrder.getBillingId()!=null){
            AddressState ba = sop.searchBillingAddress(newDeliveryOrder.getBillingId());
            newDeliveryOrder.setBillingStreet(ba.getStreet());
            newDeliveryOrder.setBillingCity(ba.getCity());
            newDeliveryOrder.setBillingState(ba.getState());
            newDeliveryOrder.setBillingCode(ba.getCode());
            newDeliveryOrder.setBillingCountry(ba.getCountry());
        }
        
    }
    
    public void handleShippingAddressChange2() {
        System.out.println("Handle Shipping Address Change");

        if (newShipGroup.getShippingId() != null) {
            AddressState sa = sop.searchShippingAddress(newShipGroup.getShippingId());
            newShipGroup.setShippingStreet(sa.getStreet());
            newShipGroup.setShippingCity(sa.getCity());
            newShipGroup.setShippingState(sa.getState());
            newShipGroup.setShippingCode(sa.getCode());
            newShipGroup.setShippingCountry(sa.getCountry());
        }

    }
    
     public void handleShippingAddressChange(){
        System.out.println("Handle Shipping Address Change");

        if(newDeliveryOrder.getShippingId()!=null){
            AddressState sa = sop.searchShippingAddress(newDeliveryOrder.getShippingId());
            newDeliveryOrder.setShippingStreet(sa.getStreet());
            newDeliveryOrder.setShippingCity(sa.getCity());
            newDeliveryOrder.setShippingState(sa.getState());
            newDeliveryOrder.setShippingCode(sa.getCode());
            newDeliveryOrder.setShippingCountry(sa.getCountry());
        }
        
    }

    public String getShippingCompany() {
        return shippingCompany;
    }

    public void setShippingCompany(String shippingCompany) {
        this.shippingCompany = shippingCompany;
    }
     
     

     public void executeDeliveryOrder(ActionEvent event){
         
           if(selectedViewDeliveryOrder.getStatus().equals("Picked")){
            System.out.println("Execute Delivery Order");
         
         imm.executeDeliveryOrder(selectedViewDeliveryOrder.getId(), shippingCompany);
             try {
                 FacesContext.getCurrentInstance().getExternalContext().redirect("deliveryOrders.xhtml");
             } catch (IOException ex) {
                 ex.printStackTrace();
             }

         }else {
            System.out.println("Status not picked!");
            FacesContext context = FacesContext.getCurrentInstance();  
          
            context.addMessage(null, new FacesMessage("Delivery Order not executed!", "Status has not been picked."));  
       
        }
         

     }

    /**
     * @return the selectedPrintDeliveryOrders
     */
    public DeliveryOrderState getSelectedPrintDeliveryOrders() {
        return selectedPrintDeliveryOrders;
    }

    /**
     * @param selectedPrintDeliveryOrders the selectedPrintDeliveryOrders to set
     */
    public void setSelectedPrintDeliveryOrders(DeliveryOrderState selectedPrintDeliveryOrders) {
        System.out.println("SET SELECTED PRINT DELIVERY ORDER");
        if(selectedPrintDeliveryOrders!=null){System.out.println("DELIVERY ORDER NOT NULL");}
        this.selectedPrintDeliveryOrders = selectedPrintDeliveryOrders;
        System.out.println("ID : "+selectedPrintDeliveryOrders.getId());
        this.setSelectedPrintDeliveryOrderID(selectedPrintDeliveryOrders.getId());
        
        //FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectedViewInquiryID",selectedViewInquiryID);
        selectedProductList=sop.viewProductListforSalesDocument(selectedPrintDeliveryOrders.getId());
        this.setSelectedProductList(selectedProductList);
    }

    /**
     * @return the selectedPrintDeliveryOrderID
     */
    public Long getSelectedPrintDeliveryOrderID() {
        return selectedPrintDeliveryOrderID;
    }

    /**
     * @param selectedPrintDeliveryOrderID the selectedPrintDeliveryOrderID to set
     */
    public void setSelectedPrintDeliveryOrderID(Long selectedPrintDeliveryOrderID) {
        this.selectedPrintDeliveryOrderID = selectedPrintDeliveryOrderID;
    }
    
     public void generateDeliveryOrderReport(ActionEvent event) throws ServletException{
                 System.out.println("TRY TO GENERATE REPORT ");
        try
        { 
            if(selectedPrintDeliveryOrders != null){
            System.out.print("managedbean1");
           //  FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectedPrintInquiry", selectedPrintInquiry);
             Long selectedPrintDeliveryOrderID = selectedPrintDeliveryOrders.getId();
             FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedPrintDeliveryOrderID", selectedPrintDeliveryOrderID);
             FacesContext.getCurrentInstance().getExternalContext().redirect("http://localhost:8181/MerlionERP-war/deliveryOrderServlet");
            System.out.print("managedbean2");
            }else{
               System.out.println("selectedPrintDeliveryOrder is null"); 
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

}

    
    
